package org.hit.burkun.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 可以序列化的矩阵
 * @author burkun
 *
 */
public class SerializableMatrix implements Serializable{

	/**
	 * auto generation
	 */
	private static final long serialVersionUID = -3815547619273089137L;

	private Map<String, Integer> nodesMap = new HashMap<>();
	private int m;
	private int n;
	private int curIndex = 0;
	private double[][] data;
	public SerializableMatrix(int m, int n){
		this.m = m;
		this.n = n;
		data = new double[m][n];
	}
	
	public void addRealtion(String mid1, String mid2, double score){
		int idx1, idx2;
		if(nodesMap.containsKey(mid1)){
			idx1 = nodesMap.get(mid1);
		}else{
			idx1 = curIndex;
			nodesMap.put(mid1, curIndex++);
		}
		if(nodesMap.containsKey(mid2)){
			idx2 = nodesMap.get(mid2);
		}else{
			idx2 = curIndex;
			nodesMap.put(mid2, curIndex++);
		}
		if(idx1 > m || idx2 > n){
			throw new IllegalArgumentException("the over the max size of matrix");
		}
		data[idx1][idx2] = score;
	}
	
	public double getScore(String mid1, String mid2){
		if(!nodesMap.containsKey(mid1) || !nodesMap.containsKey(mid2)){
			throw new IllegalArgumentException("can not find the idx of matrix!");
		}
		return data[nodesMap.get(mid1)][nodesMap.get(mid2)];
	}
	
	public int getM(){
		return m;
	}
	
	public int getN(){
		return n;
	}
	
	
	public static void writeObject(File file, SerializableMatrix sm) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(sm);
		oos.close();
	}

	public static SerializableMatrix readObject(File file){
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			return (SerializableMatrix)ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}finally{
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
